package org.baicaixiaozhan.tenet.io;

import com.google.common.annotations.Beta;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.baicaixiaozhan.tenet.base.FileType;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * DESC: 简单的文档处理工具类（二次封装）
 *
 * @author baicaixiaozhan
 * @since 1.0.0
 */
@Beta
public class SimpleDocuments {

    private SimpleDocuments() {
        throw new AssertionError();
    }

    @SneakyThrows
    private static File getTemplateFile(String template) {
        ClassPathResource resource = new ClassPathResource("wordTemplate/" + template);
        InputStream inputStream = resource.getInputStream();
        File file = File.createTempFile("temp_file_" + UUID.randomUUID().toString(), template.substring(template.lastIndexOf(".")));
        FileUtils.copyInputStreamToFile(inputStream, file);
        return file;
    }

    /**
     * doc、docx 转 pdf
     *
     * @param file
     * @return
     */
    @Deprecated
    @SneakyThrows
    public static File wordToPdf(File file) {
        File templateFile = getTemplateFile("template_pdf.pdf");
        Document document = new Document(new FileInputStream(file));
        document.saveToFile(new FileOutputStream(templateFile), FileFormat.PDF);
        return templateFile;
    }

    /**
     * convert docx to pdf
     *
     * @param file
     * @return
     */
    @SneakyThrows
    public static File docxToPdf(File file) {
        File templateFile = getTemplateFile("template_pdf.pdf");
        XWPFDocument xwpfDocument = new XWPFDocument(new FileInputStream(file));
        PdfConverter.getInstance().convert(xwpfDocument,
                new FileOutputStream(templateFile), PdfOptions.create());
        return templateFile;
    }



    /**
     * doc、docx 转 html
     *
     * @param file
     * @return
     */
    @SneakyThrows
    public static File wordToHtml(File file) {
        File templateFile = getTemplateFile("export_template_html.html");
        Document document = new Document(new FileInputStream(file));
        document.saveToFile(new FileOutputStream(templateFile), FileFormat.Html);
        return templateFile;
    }

    /**
     * 下载
     *
     * @param fileName
     * @param file
     * @param fileType
     * @param response
     */
    @SneakyThrows
    public static void download(String fileName, File file, FileType fileType,
                                HttpServletResponse response) {
        response.addHeader("Content-Length", String.valueOf(file.length()));
        download(fileName, new FileInputStream(file), fileType, response);
    }

    /**
     * 下载
     *
     * @param fileName
     * @param inputStream
     * @param fileType
     * @param response
     */
    @SneakyThrows
    public static void download(String fileName, InputStream inputStream, FileType fileType,
                                HttpServletResponse response) {
        // 以流的形式下载文件
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        // 清空 response
        response.reset();
        // 设置 response 的 Header
        String fullFileName = "";
        if (FileType.DOCX.equals(fileType)) {
            fullFileName = URLEncoder.encode(fileName + ".docx", "UTF-8");
        } else if (FileType.DOC.equals(fileType)) {
            fullFileName = URLEncoder.encode(fileName + ".doc", "UTF-8");
        } else if (FileType.PDF.equals(fileType)) {
            fullFileName = URLEncoder.encode(fileName + ".pdf", "UTF-8");
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + fullFileName);
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
}
